﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool : MonoBehaviour
{
    private List<SingleUnit> unitsPool = new List<SingleUnit>();

    private static ObjectPool _instance;

    public static ObjectPool Instance
    {
        get
        {
            if (_instance == null)
            {
                //动态的生成一个名为“GameObjectPool”的对象并将单例脚本附加上去
                _instance = new GameObject("ObjectPool").AddComponent<ObjectPool>();
            }
            return _instance;
        }
    }

    public SingleUnit TakeOne(int x, int y, UnitType type)
    {
        
        if (unitsPool.Count == 0)
		{
			return UnitsMgr.instance.CreateNewUnit(x, y, type);
		}
		else
		{
			//取出对象池里面的第一个元素
			var unit = unitsPool[0];
            unit.gameObject.SetActive(true);
			unitsPool.Remove(unit);
			return unit;
		}
    }

    //向对象池里面存对象
    public void PutBack(SingleUnit unit)
    {
        //将传进来的对象隐藏（处于非激活状态）
        unit.gameObject.SetActive(false);
        //添加到对象池中（添加到集合中） 
        unitsPool.Add(unit);
    }

    public void PutBack(GameObject unitHolder)
	{
        var unit = unitHolder.GetComponent<SingleUnit>();
        if (!unit)
        {
            Debug.LogError("not correct object");
            return;
        }
        PutBack(unit);
	}
}
 